package cn.xiaoyacode.ddd.infrastructure.persistence.mysql.mapper.user;


import cn.xiaoyacode.ddd.infrastructure.persistence.mysql.po.user.UserPO;
import cn.xiaoyacode.ddd.infrastructure.utils.query.QueryWrapperX;
import cn.xiaoyacode.ddd.ui.dto.user.req.UserListQueryReqDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;
import java.util.Objects;
import java.util.Optional;


/**
 * @author xieya
 * @date 2021/7/15
 */
@Mapper
public interface UserMapper extends BaseMapper<UserPO> {
    /**
     * 用户查询
     *
     * @param queryReqDParam 列表查询参数
     * @return
     */
    default List<UserPO> selectUserList(UserListQueryReqDTO queryReqDParam) {
        QueryWrapperX<UserPO> queryWrapperX = new QueryWrapperX<>();
        queryWrapperX
                .eqIfPresent("id", queryReqDParam.getUserId())
                .eqIfPresent("name", queryReqDParam.getUsername())
                .eq("deleted", 0)
                .eq("status", 1);
        return selectList(queryWrapperX);
    }

    /**
     * 统计用户的总数
     *
     * @param username 用户名
     * @return
     */
    default Integer selectCount(String username) {
        QueryWrapper<UserPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", username);
        return selectCount(queryWrapper);
    }

    /**
     * 分页条件
     *
     * @param queryReqDParam 查询条件
     * @return
     */
    default LambdaQueryWrapper<UserPO> isPageConditions(UserListQueryReqDTO queryReqDParam) {
        LambdaQueryWrapper<UserPO> queryWrapper = new LambdaQueryWrapper<>();
        Optional.ofNullable(queryReqDParam).ifPresent(item -> {
            if (Objects.nonNull(item.getUserId())) {
                queryWrapper.eq(UserPO::getId, item.getUserId());
            }
            if (StringUtils.isNotBlank(item.getUsername())) {
                queryWrapper.eq(UserPO::getName, item.getUsername());
            }
        });
        return queryWrapper.eq(UserPO::getDeleted, 0).eq(UserPO::getStatus, 1);
    }
}
